import React from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { PRIORITY_MODULES, MODULE_DEFAULT_ROUTE_MAP } from '@util/constants';
import _ from 'lodash';

const Index = props => {
  // 计算下次跳转
  const { accessMap } = props;
  const canAccessModules = Object.keys(accessMap);
  let nextModule = '';
  canAccessModules.forEach(module => {
    if (!nextModule && PRIORITY_MODULES.indexOf(module) !== -1) {
      nextModule = module;
    }
  });
  if (!nextModule) {
    nextModule = canAccessModules[0];
  }
  let nextRoute = MODULE_DEFAULT_ROUTE_MAP[nextModule];

  if (!nextRoute || nextRoute === '/') {
    nextRoute = '/404';
  }
  return <Redirect to={nextRoute} />;
};

Index.propTypes = {
  accessMap: PropTypes.object
};

const mapStateToProps = state => {
  return {
    accessMap: _.get(state, 'auth.user.accessMap', {})
  };
};

export default connect(
  mapStateToProps,
  null
)(Index);
